#pragma once
#include <iostream>
#include <string>
#include <unordered_map>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>

#include "log.hpp"

Log lg;

const std::string default_ip = "0.0.0.0";
const uint16_t default_port = 8080;

const int size = 1024;

class Server
{
public:
    Server(uint16_t port = default_port, std::string ip = default_ip)
    : _socketfd(-1)
    , _ip(ip)
    , _port(port)
    {}

    ~Server()
    {
        if(_socketfd >= 0)
        {
            close(_socketfd);
            _socketfd = -1;
        }
    }

    void Init()
    {
        _socketfd = socket(AF_INET, SOCK_DGRAM, 0);
        if(_socketfd == -1)
        {
            lg(Fatal, "套接字创建失败");
            exit(0);
        }
        lg(Info, "套接字创建成功");

        struct sockaddr_in server_sock;
        bzero(&server_sock, sizeof(server_sock));
        server_sock.sin_family = AF_INET;
        server_sock.sin_port = htons(_port);
        server_sock.sin_addr.s_addr = inet_addr(_ip.c_str());
        socklen_t len = sizeof(server_sock);
        if(bind(_socketfd, (const struct sockaddr*)&server_sock, len) == -1)
        {
            lg(Fatal, "bind err");
            exit(0);
        }
        lg(Info, "bind success");
    }

    void CheckClient(const struct sockaddr_in& client_sock, const std::string& clientip, const uint16_t& clientport)
    {
        auto iter = _clientlist.find(clientip);
        if(iter == _clientlist.end())
        {
            _clientlist.insert({clientip, client_sock});
            std::cout << "[" << clientip << ":" << clientport << "] add to online user." << std::endl;
            std::string message = "[";
            message += clientip;
            message += ":";
            message += std::to_string(clientport);
            message += "]";
            message += "add to online user";
            Broadcast(message);
        }
    }

    void Broadcast(const std::string& message)
    {
        for(const auto& client : _clientlist)
        {
            socklen_t len = sizeof(client.second);
            sendto(_socketfd, message.c_str(), message.size(), 0, (struct sockaddr*)&(client.second), len);
        }
    }

    void Run()
    {
        while (1)
        {
            char inbuffer[size];
            struct sockaddr_in clientsock;
            socklen_t len = sizeof(clientsock);
            ssize_t n = recvfrom(_socketfd, inbuffer, sizeof(inbuffer)-1, 0, (struct sockaddr*)&clientsock, &len);
            if(n < 0)
            {
                lg(Warning, "recvfrom err");
                continue;
            }
            inbuffer[n] = 0;

            std::string clientip = inet_ntoa(clientsock.sin_addr);
            uint16_t clientport = ntohs(clientsock.sin_port);
            CheckClient(clientsock, clientip, clientport);

            std::string message = "[";
            message += clientip;
            message += ":";
            message += std::to_string(clientport);
            message += "]#";
            message += inbuffer;
            Broadcast(message);
        }
    }

private:
    int _socketfd;
    std::string _ip;
    uint16_t _port;
    std::unordered_map<std::string, struct sockaddr_in> _clientlist;
};